package main

import (
	"flag"
	"fmt"
	"os"
	"regexp"

	"./conf"
	"./source"
)

var funcName string

var (
	h bool
	v bool
	e string
)

func init() {
	flag.BoolVar(&h, "h", false, "get help")
	flag.BoolVar(&v, "v", false, "show version")

	flag.StringVar(&e, "e", "", "change translate engine")

	// 改变默认的 Usage
	flag.Usage = usage
}

func usage() {
	fmt.Fprintf(os.Stderr, `go tranlation tools
Usage: tl [keyword] [-hv] [-e engine] 
Options:
`)
	flag.PrintDefaults()
}

// flag处理
func flagExec() {
	if h {
		flag.Usage()
		os.Exit(0)
	}
	if v {
		fmt.Println("Version 1.0.0")
		os.Exit(0)
	}

	if e != "" { //设置翻译引擎
		if e != "baidu" && e != "youdao" && e != "jinshan" && e != "tencent" && e != "tencentAi" {
			fmt.Println("Engine only support in `baidu`,`youdao`,`jinshan`,`tencent`,`tencentAi`")
		} else {
			conf.SetEngine(e)
			fmt.Println("Set engine success!")
		}
		os.Exit(0)
	}
}

func main() {
	flag.Parse()

	flagExec()

	userArgs := os.Args
	if len(userArgs) == 1 {
		fmt.Println("Usage: tl [keyword] [-hv] [-e engine]. \nmore info for help `tl -h`")
		os.Exit(0)
	}
	// fmt.Println(userArgs)

	var fromType string
	var words string
	args := userArgs[1]

	//获取相关配置
	conf := conf.GetConf()

	if isZh, _ := regexp.MatchString(`[\p{Han}]+`, args); isZh {
		fromType = "zh"
		words = args
	} else if isEn, _ := regexp.MatchString(`[a-zA-Z]`, args); isEn {
		fromType = "en"

		for index := 1; index < len(userArgs); index++ {
			words += userArgs[index] + " "
		}
	}

	//结果
	var wordMeans []string
	if conf.Engine == "youdao" { //有道
		wordMeans = source.TranslateYoudao(words, fromType)
	} else if conf.Engine == "jinshan" { //金山词霸
		wordMeans = source.TranslateJinshan(words, fromType)
	} else if conf.Engine == "tencent" { //腾讯翻译君翻译
		wordMeans = source.TranslateTencent(words, fromType)
	} else if conf.Engine == "tencentAi" { //腾讯AI Labi翻译
		wordMeans = source.TranslateTencentAi(words, fromType)
	} else { //百度
		wordMeans = source.TranslateBaidu(words, fromType)
	}

	var resultStr string
	gohostos := os.Getenv("OS")
	ssh := os.Getenv("SSH_ASKPASS") //是否在git的ssh中（支持ansi）
	for i := 0; i < len(wordMeans); i++ {
		if gohostos == "Windows_NT" && ssh == "" {
			resultStr = fmt.Sprintf("%s\n\r%d:  %s", resultStr, i+1, wordMeans[i])
		} else { //linux unix输出颜色
			resultStr = fmt.Sprintf("%s\n\r\033[0;33m%d:\033[0m  \033[1m%s\033[0m", resultStr, i+1, wordMeans[i])
		}
	}
	if gohostos == "Windows_NT" && ssh == "" {
		fmt.Printf("%s  %s \n\r结果：%s", conf.Engine, words, resultStr)
	} else {
		fmt.Printf("[\033[0;36m%s\033[0m]  %s \n\r结果：%s", conf.Engine, words, resultStr)
	}
}
